package com.hlingsoft.kkh.action.admin;

import com.google.gson.Gson;
import com.hlingsoft.kkh.constant.MerchantConst;
import com.hlingsoft.kkh.dao.AdminMerchantCategoryDao;
import com.hlingsoft.kkh.dao.MerchantDao;
import com.hlingsoft.kkh.entity.Admin;
import com.hlingsoft.kkh.entity.MerchantInfo;
import com.hlingsoft.kkh.entity.vo.JsonVo;
import com.hlingsoft.kkh.entity.vo.PageVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by selbylei on 2015/1/15.
 */
@Controller
@RequestMapping("/admin/merchant")
public class AdminMerchantAction extends AdminBaseAction {
    @Autowired
    private MerchantDao merchantDao;
    @Autowired
    private AdminMerchantCategoryDao merchantCategoryDao;

    @RequestMapping(value = "/page.htm", method = RequestMethod.GET)
    public String allList(@RequestParam(value = "p", defaultValue = "1") int pageNum, HttpServletRequest request,
                          ModelMap modelMap) {
        PageVo<MerchantInfo> pageVo = new PageVo<MerchantInfo>(pageNum);
        pageVo.setRows(10);
        pageVo.basePath = "admin/merchant/page.htm";
        pageVo.setList(merchantDao.getMerchantAllList(pageVo.getOffset(), pageVo.getRows()));
        pageVo.setCount(merchantDao.getMerchantDaoListCount());
        modelMap.put("pageVo", pageVo);
        modelMap.put("merchantName", "");
        modelMap.put("merchantType","");
        //商户分类传递给前台
        modelMap.put("merchantCategoryList",merchantCategoryDao.getMerchantCategoryList());
        return "system/merchant/all";
    }

    @RequestMapping(value = "/delete.json")

    @ResponseBody
    public JsonVo<String> delete(@RequestParam(value = "merchantId") long merchantId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        merchantDao.deleteMerchant(merchantId);
        json.setResult(true);
        return json;
    }

    @RequestMapping(value = "/detail.htm")
    public String detail(@RequestParam(value = "merchantId") long merchantId,
                         HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        modelMap.put("merchant", merchantDao.getMerchantById(merchantId));
        Admin admin= getAdmin(request)      ;//获取管理员信息
        if(admin.getRole() ==0){
            modelMap.put("auditShow", "yes");

        }  else{
            modelMap.put("auditShow", "no");
        }
        modelMap.put("merchantCategoryList",merchantCategoryDao.getMerchantCategoryList());
        return "system/merchant/edit";
    }


    @RequestMapping(value = "/toAdd.htm", method = RequestMethod.GET)
    public String toAdd(HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        modelMap.put("merchantCategoryList",merchantCategoryDao.getMerchantCategoryList());

        Admin admin= getAdmin(request)      ;//获取管理员信息
        if(admin.getRole() ==0){
            modelMap.put("auditShow", "yes");

        }  else{
            modelMap.put("auditShow", "no");
        }
        return "system/merchant/add";
    }

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");

    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonVo<String> add(
            @RequestParam(value = "name") String name,
                @RequestParam(value = "credentials") String credentials,
            @RequestParam(value = "merchantType") String merchantType,
            @RequestParam(value = "address") String address,
            @RequestParam(value = "province") String province,
            @RequestParam(value = "city") String city,
            @RequestParam(value = "area", required = false) String area,
            @RequestParam(value = "contact") String contact,
            @RequestParam(value = "contact_tel") String contact_tel,
            @RequestParam(value = "fixed_tel") String fixed_tel,
            @RequestParam(value = "latitude") String latitude,
            @RequestParam(value = "longitude") String longitude,
            @RequestParam(value = "description") String description,
            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {
            json.setResult(true);
            MerchantInfo merchantInfo = new MerchantInfo();
            merchantInfo.setMerchantName(name);
            merchantInfo.setMerchantType(Integer.valueOf(merchantType));

            if(!StringUtils.isEmpty(credentials) && credentials.endsWith(","))    {
                credentials=credentials.substring(0,credentials.length()-1);

            }
            merchantInfo.setCredentials(credentials);
            merchantInfo.setIsAttestation(MerchantConst.IsAttestation.no);
            merchantInfo.setScore(0);
            merchantInfo.setAddress(address);
            merchantInfo.setContact(contact);
            merchantInfo.setContact_tel(contact_tel);
            merchantInfo.setFixed_tel(fixed_tel);
            merchantInfo.setLatitude(Float.valueOf(latitude));
            merchantInfo.setLongitude(Float.valueOf(longitude));
            merchantInfo.setProvince(province);
            merchantInfo.setCity(city);
            if (StringUtils.isEmpty(area))
                area = "";
            merchantInfo.setArea(area);
            merchantInfo.setCreateTime(new Date());
            merchantInfo.setUpdateTime(new Date());
            merchantInfo.setDescription(description);
            merchantInfo.setStatus(MerchantConst.Status.audit);
            merchantDao.addMerchant(merchantInfo);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonVo<String> edit(
            @RequestParam(value = "merchantId") long merchantId,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "merchantType") String merchantType,
            @RequestParam(value = "address") String address,
            @RequestParam(value = "province") String province,
            @RequestParam(value = "city") String city,
            @RequestParam(value = "area") String area,
            @RequestParam(value = "contact") String contact,
            @RequestParam(value = "contact_tel") String contact_tel,
            @RequestParam(value = "fixed_tel") String fixed_tel,
            @RequestParam(value = "latitude") String latitude,
            @RequestParam(value = "longitude") String longitude,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "status") String status,
            @RequestParam(value = "credentials") String credentials,
            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {
            json.setResult(true);

            MerchantInfo merchantInfo = merchantDao.getMerchantById(merchantId);
            merchantInfo.setMerchantName(name);
            merchantInfo.setMerchantType(Integer.valueOf(merchantType));
            if(!StringUtils.isEmpty(credentials) &&   credentials.endsWith(","))    {
                credentials=credentials.substring(0,credentials.length()-1);

            }
            merchantInfo.setCredentials(credentials);
            if(MerchantConst.Status.valueOf(status).equals(MerchantConst.Status.audit))  {
                merchantInfo.setIsAttestation(MerchantConst.IsAttestation.yes);
            }

            merchantInfo.setScore(0);
            merchantInfo.setAddress(address);
            merchantInfo.setContact(contact);
            merchantInfo.setContact_tel(contact_tel);
            merchantInfo.setFixed_tel(fixed_tel);
            merchantInfo.setLatitude(Float.valueOf(latitude));
            merchantInfo.setLongitude(Float.valueOf(longitude));
            merchantInfo.setProvince(province);
            merchantInfo.setCity(city);
            merchantInfo.setArea(area);
            merchantInfo.setUpdateTime(new Date());
            merchantInfo.setDescription(description);

            merchantInfo.setStatus(MerchantConst.Status.valueOf(status));
            merchantDao.updateMerchant(merchantInfo);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    @RequestMapping(value = "/toSearch.htm")
    public String toSearchList(@RequestParam(value = "merchantName",required = false) String merchantName,
                               @RequestParam(value = "province",required = false)String province,
                               @RequestParam(value = "city",required = false)String city,
                               @RequestParam(value = "area",required = false)String area,
                               @RequestParam(value = "address",required = false)String address,
                               @RequestParam(value = "merchantType",required = false) String merchantType,
                               @RequestParam(value = "p", defaultValue = "1") int pageNum,
                               HttpServletRequest request, ModelMap modelMap) {

        if (request.getMethod().equals("GET")){
            merchantName = encodeStr(merchantName);
            province = encodeStr(province);
            city = encodeStr(city);
            area = encodeStr(area);
            address = encodeStr(address);
            merchantType = encodeStr(merchantType);
        }

        PageVo<MerchantInfo> pageVo = new PageVo<MerchantInfo>(pageNum);
        pageVo.setRows(10);
        Map<String, String> args = new HashMap<String, String>();
        args.put("merchantName", merchantName);
        args.put("province",province);
        args.put("city",city);
        args.put("area",area);
        args.put("address",address);
        args.put("merchantType",merchantType);
        pageVo.setArgs(args);
        pageVo.basePath = "admin/merchant/toSearch.htm";
        if(merchantType == null){
            pageVo.setList(merchantDao.getSearchMerchant(-1, merchantName, province, city, area, address, pageVo.getOffset(), pageVo.getRows()));
            pageVo.setCount(merchantDao.getSearchMerchantCount(-1, merchantName, province, city, area, address));

        } else {
            pageVo.setList(merchantDao.getSearchMerchant(Integer.valueOf(merchantType), merchantName, province, city, area, address, pageVo.getOffset(), pageVo.getRows()));
            pageVo.setCount(merchantDao.getSearchMerchantCount(Integer.valueOf(merchantType), merchantName, province, city, area, address));
        }
        modelMap.put("pageVo", pageVo);
        modelMap.put("merchantName", merchantName);
        modelMap.put("province",province);
        modelMap.put("city",city);
        modelMap.put("area",area);
        modelMap.put("address",address);
        modelMap.put("merchantType",merchantType);
        modelMap.put("merchantCategoryList",merchantCategoryDao.getMerchantCategoryList());

        return "system/merchant/all";
    }


    @RequestMapping(value = "/search.json")
    @ResponseBody
    public JsonVo<String> search(@RequestParam(value = "merchantName") String merchantName,
                                 ModelMap modelMap) {
        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        merchantName = encodeStr(merchantName);

        JsonVo<String> json = new JsonVo<String>();
        if (isContainsChinese(pat, merchantName)) {
            List<MerchantInfo> listMerchant = merchantDao.getMerchantByMerchantNameWhenJobSearch(merchantName);
            Gson gson = new Gson();
            json.setT(gson.toJson(listMerchant));
            json.setResult(true);
        } else {
            json.setResult(false);
        }
        return json;
    }

    public static boolean isContainsChinese(Pattern pat, String str) {
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find()) {
            flg = true;
        }
        return flg;

    }

    public String encodeStr(String str) {
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
